// pages/bankCards/bankCards.js
Page({
    data: {
      statusBarHeight: 0,
      bankCards: [],       // 银行卡列表
      loading: false,      // 加载状态
      selectedCardId: ''   // 选中的银行卡ID
    },
  
    onLoad() {
      // 获取状态栏高度
      const systemInfo = wx.getSystemInfoSync();
      this.setData({
        statusBarHeight: systemInfo.statusBarHeight
      });
      
      // 加载银行卡列表
      this.getBankCards();
    },
  
    onShow() {
      // 每次显示页面时刷新银行卡列表
      this.getBankCards();
    },
  
    // 获取银行卡列表
    getBankCards() {
      if (this.data.loading) return;
      
      this.setData({ loading: true });
      
      wx.cloud.callFunction({
        name: 'getUserBankCards',
        data: {
          userId: wx.getStorageSync('userInfo')._id
        },
        success: (res) => {
            console.log(res);
          if (res.result.success) {
            const cards = res.result.cards || [];
            let selectedCardId = '';
            
            // 查找默认卡
            const defaultCard = cards.find(card => card.isDefault);
            if (defaultCard) {
              selectedCardId = defaultCard._id;
            } else if (cards.length > 0) {
              selectedCardId = cards[0]._id;
            }
            
            this.setData({
              bankCards: cards,
              selectedCardId: selectedCardId
            });
          }
        },
        fail: (err) => {
          console.error('获取银行卡列表失败:', err);
          wx.showToast({
            title: '获取银行卡列表失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.setData({ loading: false });
        }
      });
    },
  
    // 选择银行卡（用于提现页面回传）
    selectBankCard(e) {
        console.log(e);
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      console.log(prevPage);
      // 如果上一页是提现页面，回传选中的银行卡
      if (prevPage.route == 'pages/withdrawPoints/withdrawPoints') {
        const cardId = e.currentTarget.dataset.id;
        prevPage.setData({
          selectedCardId: cardId
        });
        wx.navigateBack();
      }
    },
  
    // 设置默认卡
    setDefaultCard(e) {
      const cardId = e.currentTarget.dataset.id;
      const cardIndex = e.currentTarget.dataset.index;
      
      // 如果已经是默认卡，不做处理
      if (this.data.bankCards[cardIndex].isDefault) return;
      
      wx.showLoading({
        title: '设置中...'
      });
      
      wx.cloud.callFunction({
        name: 'setDefaultBankCard',
        data: {
          userId: wx.getStorageSync('userInfo')._id,
          cardId: cardId
        },
        success: (res) => {
          if (res.result.success) {
            wx.showToast({
              title: '设置成功',
              icon: 'success'
            });
            this.getBankCards();  // 刷新列表
          } else {
            wx.showToast({
              title: '设置失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('设置默认卡失败:', err);
          wx.showToast({
            title: '设置失败',
            icon: 'none'
          });
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    },
  
    // 删除银行卡
    deleteCard(e) {
      const cardId = e.currentTarget.dataset.id;
      const cardIndex = e.currentTarget.dataset.index;
      const card = this.data.bankCards[cardIndex];
      
      wx.showModal({
        title: '确认删除',
        content: `确定要删除这张${card.bankName}(${card.cardNumberDisplay})银行卡吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({
              title: '删除中...'
            });
            
            wx.cloud.callFunction({
              name: 'deleteBankCard',
              data: {
                userId: wx.getStorageSync('userInfo')._id,
                cardId: cardId
              },
              success: (res) => {
                if (res.result.success) {
                  wx.showToast({
                    title: '删除成功',
                    icon: 'success'
                  });
                  this.getBankCards();  // 刷新列表
                } else {
                  wx.showToast({
                    title: '删除失败',
                    icon: 'none'
                  });
                }
              },
              fail: (err) => {
                console.error('删除银行卡失败:', err);
                wx.showToast({
                  title: '删除失败',
                  icon: 'none'
                });
              },
              complete: () => {
                wx.hideLoading();
              }
            });
          }
        }
      });
    },
  
    // 添加银行卡
    addBankCard() {
      wx.navigateTo({
        url: '/pages/bindBankCard/bindBankCard'
      });
    },
    
    // 返回上一页
    goBack() {
      wx.navigateBack();
    }
  });